package cn.fancylab.template.web.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ui.ModelMap;

import cn.fancylab.service.DaoService;
import cn.fancylab.web.action.BaseController;
import cn.fancylab.web.util.PageUtil;

/**
 * @author <a href="mailto:acerge@163.com">gebiao(acerge)</a>
 */
public abstract class AnnotationController extends BaseController {

	@Autowired
	@Qualifier("daoService")
	protected DaoService daoService;

	protected final PageUtil getScriptPageUtil(int count, int rowsPerpage, int pageNo, Map<String, Object> params) {
		PageUtil pageUtil = new PageUtil(count, rowsPerpage, pageNo, null);
		pageUtil.initPageInfo(params);
		return pageUtil;
	}

	/**
	 * @param targetUrl
	 * @param request
	 * @param model
	 * @return
	 */
	protected String gotoLogin(String targetUrl, HttpServletRequest request, ModelMap model) {
		try {
			if (StringUtils.isNotBlank(targetUrl)) {
				String queryStr = request.getQueryString();
				String paramStr = "";
				if (StringUtils.isNotBlank(queryStr) && StringUtils.length(queryStr) < 300) {
					paramStr = URLDecoder.decode(queryStr, "utf-8");
				}
				targetUrl += targetUrl.indexOf('?') > 0 ? "&" + paramStr : "?" + paramStr;

				return showRedirect("login.xhtml?TARGETURL=" + URLEncoder.encode(targetUrl, "utf-8"), model);
			}
		} catch (UnsupportedEncodingException e) {// ignore
		}
		return showRedirect("login.xhtml", model);
	}
}